<?php

namespace App\Http\Controllers\OpenShop\FeishuMini;

use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\OpenShop\Feishu\SiteMissionController;
use App\Http\Middleware\OpenShop\AppletAuth;
use App\Http\Resources\OpenShop\ShopLocation\PlaceHolderSiteLocationResource;
use App\Http\Validate\OpenShop\ShopEngineeringConstruction\ShopEngineeringConstructionValidate;
use App\Rules\Mobile;
use App\Service\OpenShop\Feishu\PermissionService;
use App\Service\OpenShop\Feishu\ShopCheckAcceptService;
use App\Service\OpenShop\Feishu\ShopEngineeringConstructionService;
use App\Service\OpenShop\Feishu\SiteMissionService;
use App\Service\OpenShop\Feishu\SpaceDesignService;
use App\Service\OpenShop\Merchant\OrderProgressService;
use App\Service\OpenShop\SiteLocation\AuthService;
use App\Service\OpenShop\SiteLocation\PlaceHolderSiteLocationService;
use App\Service\Rms\ShopService;
use Illuminate\Http\Request;

class MissionController extends BaseController
{
    public function lists(Request $request)
    {
        $status         = $request->get('status', SiteMissionEnum::STATUS_1);
        $pageNum        = (int)$request->get('pageNum', 1);
        $pageSize       = (int)$request->get('pageSize', 20);
        $search         = (string)$request->get('search');
        $dataPermission = PermissionService::dataPermission(PermissionService::URI_SIGN_ORDER);
        $userId         = getRmsUserInfoByAuth()->id;
        // isAll && 原生sql
        $orderPermission = (new PermissionService)->getOrderPermissionDataOrder($dataPermission, $userId);

        return $this->success(SiteMissionService::miniMissionLists($status, $pageNum, $pageSize, $orderPermission,
            $userId, $search));
    }

    public function listsCount(Request $request)
    {
        $search          = (string)$request->get('search');
        $dataPermission  = PermissionService::dataPermission(PermissionService::URI_SIGN_ORDER);
        $userId          = getRmsUserInfoByAuth()->id;
        $orderPermission = (new PermissionService)->getOrderPermissionDataOrder($dataPermission, $userId);

        return $this->success(SiteMissionService::miniMissionListsCount($orderPermission, $userId, $search));
    }

    public function baseInfo(Request $request, int $id)
    {
        $mission = SiteMissionService::siteInfo($id);

        $result = [
            'mission' => $mission
        ];

        if ($mission['stepStatus'] == MissionTemplateEnum::STEP_STATUS_3) {
            $placeholder = new PlaceHolderSiteLocationService($mission['orderNo']);

            $placeholderInfo = empty($placeholder->getPlaceholderInfo()) ? null :
                PlaceHolderSiteLocationResource::collection([$placeholder->getPlaceholderInfo()])
                                               ->getIterator()->current();
            $result          = array_merge($result, [
                'placeholderInfo' => $placeholderInfo
            ]);
        }

        return $this->success($result);
    }

    public function buildInfo(Request $request)
    {
        $this->validate($request, [
            'orderNo' => 'required|string'
        ]);
        return $this->success(SiteMissionService::buildInfo($request->orderNo));
    }

    public function preparationConfirm(Request $request)
    {
        $this->validate($request, [
            'orderNo'     => 'required|string',
            'shopName'    => 'required|string',
            'phoneNumber' => new Mobile(),
        ]);
        if (strpos($request->shopName, '的店') !== false) {
            return $this->fail(403, '门店名称不符合规范');
        }

        //修改名店名称
        ShopService::updateShopName($request->orderNo, $request->shopName);
        //确认建店信息
        $actuallyParams = (object)[
            'orderNo'     => $request->orderNo,
            'managerId'   => $request->get('managerId', 0),
            'managerName' => $request->get('managerName', ''),
        ];

        ShopCheckAcceptService::onlyAssignManager(getRmsUserInfoByAuth(), $actuallyParams);

        SpaceDesignService::preparationConfirm($request->orderNo, AppletAuth::$userInfo->userId,
            AppletAuth::$userInfo->username, $request->receiverName, $request->phoneNumber, $request->regions,
            $request->addressDetail);
        return $this->success();
    }

    public function constructionInfo(Request $request)
    {
        $this->validate($request, [
            'orderNo' => 'required|string',
        ]);
        return $this->success(SiteMissionService::constructionInfo($request->orderNo));
    }


    /**
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Exception
     */
    public function constructionStart(Request $request)
    {
        $requestParams  = $request->all();
        $actuallyParams = ShopEngineeringConstructionValidate::engineeringConstructionStartValidate($requestParams);
        $userInfo       = (object)['id' => AppletAuth::$userInfo->userId];
        ShopEngineeringConstructionService::engineeringConstructionStart($userInfo, $actuallyParams);
        return $this->success();
    }

    /**
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Exception
     */
    public function constructionFinish(Request $request)
    {
        $requestParams = $request->all();
        $finishData    = ShopEngineeringConstructionValidate::engineeringConstructionFinish($requestParams);
        ShopEngineeringConstructionValidate::attachValidate($requestParams,
            OrderProgressService::PROGRESS_ORIGIN_APPLET);
        $userInfo = (object)[
            'id' => AppletAuth::$userInfo->userId,
        ];
        ShopEngineeringConstructionService::engineeringConstructionFinish($userInfo, $finishData, (object)[]);
        return $this->success();
    }

    public function constructionInput(Request $request)
    {
        $this->validate($request, [
            'orderNo' => 'required|string'
        ]);
        return $this->success(['inputs' => SiteMissionService::constructionInput($request->orderNo)]);
    }

    public function constructionUpdate(Request $request)
    {
        //对订单状态做验证  防止已提交后修改数据
        ShopEngineeringConstructionValidate::engineeringConstructionRealTimeUpdate($request->all());
        SiteMissionService::constructionUpdate($request->all(), AppletAuth::$userInfo);
        return $this->success();
    }
}
